const SparkMD5 = require('spark-md5');

/***
 *
 * @param k 文件Blob
 */
const parseMD5 = (k: Blob) => {
  return new Promise((resolve) => {
    const fileReader = new FileReader();
    fileReader.readAsBinaryString(k);
    fileReader.onload = function (e) {
      // @ts-ignore
      resolve(SparkMD5.hashBinary(e.target.result));
    };
  });
};

const batchParseMd5 = (arr: any) => {
  // @ts-ignore
  const promiseArr = [];
  const len = arr.length;
  for (let i = 0; i < len; i++) {
    promiseArr.push(parseMD5(arr[i]));
  }
  return new Promise((resolve) => {
    // @ts-ignore
    Promise.all(promiseArr).then((r) => {
      resolve(r);
    });
  });
};

/***
 *
 * @param file input上传后的Blob
 * @param spliceSize 切分出每块的大小
 */
const sliceFile = (file: any, spliceSize = 1024 * 1024) => {
  // 如何计算切分起始点
  const fullSize = file.size;
  const pieces = Math.ceil(fullSize / spliceSize);
  const blobPool = [];
  for (let i = 0; i < pieces; i++) {
    blobPool.push(file.slice(i * spliceSize, (i + 1) * spliceSize));
  }
  return blobPool;
};

const sliceFileWithMd5 = async (file: any, spliceSize = 1024 * 1024) => {
  // 如何计算切分起始点
  const fullSize = file.size;
  const pieces = Math.ceil(fullSize / spliceSize);
  const blobPool = [];

  for (let i = 0; i < pieces; i++) {
    const filed = file.slice(i * spliceSize, (i + 1) * spliceSize);
    blobPool.push({
      file: filed,
      md5: await parseMD5(filed),
      fileInfo: {
        name: file.name,
        size: file.size,
        type: file.type,
      },
    });
  }
  return blobPool;
};

export { parseMD5, sliceFile, batchParseMd5, sliceFileWithMd5 };
